package com.dwxt.cdms.admin.service;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.dwxt.cdms.base.OperateCategory;
import com.dwxt.cdms.dao.AdminUserMapper;
import com.dwxt.cdms.dao.RoleMapper;
import com.dwxt.cdms.dao.RoleMenuMapper;
import com.dwxt.cdms.entity.*;
import com.dwxt.cdms.entity.dto.AdminUserDTO;
import com.dwxt.cdms.entity.vo.AdminUserVO;
import com.dwxt.cdms.entity.vo.MenuVO;
import com.dwxt.cdms.service.StationService;
import com.dwxt.cdms.util.RedisUtil;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.base.YesOrNo;
import com.dwxt.common.util.MD5Utils;
import com.dwxt.common.util.PartyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceAdmin {
    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private UserRoleServiceAdmin userRoleServiceAdmin;

    @Autowired
    private MenuServiceAdmin menuServiceAdmin;

    @Autowired
    private HistoryServiceAdmin historyServiceAdmin;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private StationService stationService;

    @Autowired
    private SendSmsRequest sendSmsRequest;

    @Autowired
    private IAcsClient iAcsClient;

    /**
     * 根据名字查找用户
     *
     * @param phone
     * @return AdminUser
     */
    public AdminUser selectByPhone(String phone) {

        AdminUserExample example = new AdminUserExample();
        example.createCriteria().andPhoneEqualTo(phone);
        List<AdminUser> adminUsers = adminUserMapper.selectByExample(example);
        return adminUsers.isEmpty() ? null : adminUsers.get(0);
    }

    /**
     * 校验用户名和密码
     *
     * @param phone
     * @param password
     * @return
     */
    public AdminUser login(String phone, String password) {
        AdminUser user = selectByPhone(phone);
        if (user != null && MD5Utils.MD5Encode(password).equalsIgnoreCase(user.getPassword()) && user.getIsOn() == YesOrNo.YES) {
            return user;
        }
        return null;
    }

    /**
     * @param adminUserDTO
     * @return
     */
    @Transactional
    public BaseResult createOrUpdateUser(AdminUserDTO adminUserDTO) {
        List<Integer> roleIds = adminUserDTO.getRoleIds();
        if (roleIds == null) {
            return BaseResult.build(StatusCode.ROLE_NOT_EXIST);
        }
        StringBuilder sb = new StringBuilder();
        for (Integer roleId : roleIds) {
            sb.append(roleId).append(",");
        }
        List<String> stationIds = adminUserDTO.getStationIds();
        String stationId="";
        String station="";
        if (stationIds != null) {
            stationId = StringUtils.join(stationIds, ",");
            ArrayList<String> list = new ArrayList<>();
            for (String id : stationIds) {
                list.add(stationService.getStationById(Integer.valueOf(id)).getName());
            }
            station = StringUtils.join(list, ",");
        } else {//前端不传station，当前登录不是超级管理员时，插入当前登录人区域id
            Integer loginUserStation = stationService.getLoginUserStation();
            if (loginUserStation != null) {
                stationId = loginUserStation.toString();
                station=stationService.getStationById(loginUserStation).getName();
            }
        }
        adminUserDTO.setStationId(stationId);
        adminUserDTO.setStation(station);

        if (adminUserDTO.getId() == null) {
            AdminUser user = selectByPhone(adminUserDTO.getPhone());
            if (user == null) {
                user = new AdminUser();
                user.setPhone(adminUserDTO.getPhone());
                user.setUsername(adminUserDTO.getUsername());
                if (StringUtils.isBlank(adminUserDTO.getPassword())) {
                    adminUserDTO.setPassword("123456");
                }
                user.setPassword(MD5Utils.MD5Encode(adminUserDTO.getPassword().trim()));
                user.setStationId(stationId);
                user.setStation(station);
                int i = adminUserMapper.insertSelective(user);
                Integer userId = user.getId();
                //批量插入用户角色
                userRoleServiceAdmin.batchInsert(userId, roleIds);
                //插入操作记录
                historyServiceAdmin.generate("新建用户" + user.getPhone(), OperateCategory.INSERT);
                return BaseResult.ok(user);
            } else {
                return BaseResult.build(StatusCode.USERNAME_EXIST);
            }
        } else {
            if (StringUtils.isNotBlank(adminUserDTO.getPassword())) {
                adminUserDTO.setPassword(MD5Utils.MD5Encode(adminUserDTO.getPassword().trim()));
            }
            if (StringUtils.isNotBlank(adminUserDTO.getUsername())) {
                adminUserDTO.setUsername(adminUserDTO.getUsername().trim());
            }
            try {
                adminUserMapper.updateByPrimaryKeySelective(adminUserDTO);
                //插入操作记录
                historyServiceAdmin.generate("修改用户:" + adminUserDTO.getId(), OperateCategory.UPDATE);
            } catch (org.springframework.dao.DuplicateKeyException e) {
                return BaseResult.build(StatusCode.USERNAME_EXIST);
            }
            if (roleIds != null && roleIds.size() != 0) {
                //修改用户的角色
                userRoleServiceAdmin.deleteByUserId(adminUserDTO.getId());
                userRoleServiceAdmin.batchInsert(adminUserDTO.getId(), roleIds);
            }
            return BaseResult.ok();
        }
    }

    public BaseResult selectAllUserVo(Integer pageSize, Integer pageNum,String name,String phone) {
        Integer stationId = stationService.getLoginUserStation();
        Integer currentUserId = Integer.valueOf(PartyUtil.getCurrentUserId());
        PageHelper.startPage(pageNum, pageSize);
        List<AdminUserVO> adminUserVOS = adminUserMapper.selectAllUserVo(stationId,name,phone,currentUserId);
        PageInfo<AdminUserVO> pageInfo = new PageInfo(adminUserVOS);
        List<AdminUserVO> list = pageInfo.getList();
        list = list.stream().map(adminUserVO -> {
            List<Role> roles = roleMapper.selectByUserId(adminUserVO.getId());
            if (roles != null) {
                adminUserVO.setRoles(roles);
                if (adminUserVO.getStationId() != null && !"".equals(adminUserVO.getStationId())) {
                    List<String> stationIds = Arrays.asList(adminUserVO.getStationId().split(","));
                    adminUserVO.setStationIds(stationIds);
                }
            }
            return adminUserVO;
        }).collect(Collectors.toList());
        pageInfo.setList(list);
        return BaseResult.ok(pageInfo);
    }


    @Transactional
    public int batchDeleteById(Integer[] id) {
        for (Integer i : id) {
            if (i == 1) {
                return 0;
            }
        }
        AdminUserExample example = new AdminUserExample();
        example.createCriteria().andIdIn(Arrays.asList(id));
        int i = adminUserMapper.deleteByExample(example);

        //批量删除用户角色记录
        userRoleServiceAdmin.deleteByUserIds(id);
        //插入操作记录
        StringBuilder sb = new StringBuilder();
        for (Integer integer : id) {
            sb.append(integer).append(",");
        }
        historyServiceAdmin.generate("删除用户:" + sb, OperateCategory.DELETE);
        return i;
    }

    public List<Integer> menuIdList(Integer id) {
        List<UserRole> userRoles = userRoleServiceAdmin.selectByUserId(id);
        List<Integer> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());

        RoleMenuExample example = new RoleMenuExample();
        example.setDistinct(true);
        example.createCriteria().andRoleIdIn(roleIds);
        List<RoleMenu> roleMenus = roleMenuMapper.selectByExample(example);
        List<Integer> collect = roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        return collect;

    }


    public AdminUser selectUser() {
        AdminUser user = adminUserMapper.selectByPrimaryKey(Integer.parseInt(PartyUtil.getCurrentUserId()));
        if (user.getId() == 1) {
            user.setSuperAdmin(true);
        } else {
            user.setSuperAdmin(false);
        }
        if (StringUtils.isNotBlank(user.getStationId())) {
            Integer integer = Integer.valueOf(user.getStationId().split(",")[0]);
            Station station = stationService.getStationById(integer);
            if (station != null) {
                user.setLat(station.getLat());
                user.setLng(station.getLng());
            }
        }
        return user;
    }

    public List<Role> selectRolesByUserId(String userId) {
        return adminUserMapper.selectRolesByUserId(userId);
    }


    public void disOrEnable(Integer id) {
        AdminUser adminUser = adminUserMapper.selectByPrimaryKey(id);
        if (adminUser.getIsOn() == YesOrNo.YES) {
            adminUser.setIsOn(YesOrNo.NO);
        } else {
            adminUser.setIsOn(YesOrNo.YES);
        }
        adminUserMapper.updateByPrimaryKeySelective(adminUser);
        //插入操作记录
        historyServiceAdmin.generate("启用或禁用用户:" + id, OperateCategory.UPDATE);
    }

    public AdminUser selectUserById(Integer id) {
        return adminUserMapper.selectByPrimaryKey(id);
    }


    public List<MenuVO> menuList(int id) {
        List<UserRole> userRoles = userRoleServiceAdmin.selectByUserId(id);
        List<Integer> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        return menuServiceAdmin.selectMenuVOByRoleIds(roleIds);
    }


    public BaseResult selectResponsibleList(Integer stationId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("communityManagerList",adminUserMapper.selectResponsibleList(13,stationId));
        map.put("healthManagerList",adminUserMapper.selectResponsibleList(5,stationId));
        map.put("doctorList",adminUserMapper.selectResponsibleList(3,stationId));
        map.put("dieticianList",adminUserMapper.selectResponsibleList(4,stationId));
        map.put("gridMemberList",adminUserMapper.selectResponsibleList(15,stationId));
        return BaseResult.ok(map);
    }

    public BaseResult sendCode(String phone)  {
        String code = String.format("%04d", new Random().nextInt(9999));
        RedisUtil.set(phone,code,180l);
        //发送验证码
        Map<String, String> map = new HashMap<String, String>();
        final String templateCode = "SMS_229467212";
        sendSmsRequest.setPhoneNumbers(phone);   //接收号码
        // 控制台创建的模板CODE
        sendSmsRequest.setTemplateCode(templateCode);
        map.put("code", code);//消息
        sendSmsRequest.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
        try {
            SendSmsResponse httpResponse = iAcsClient.getAcsResponse(sendSmsRequest);
        } catch (ClientException e) {
            return BaseResult.build(StatusCode.SEND_CODE_FAIL);
        }

        return BaseResult.ok();
    }
}
